// packageA/pages/goodsApplyList/goodsApplyList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');

Page({
  /**
   * 页面的初始数据
   */
  data: {  
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索词
    searchValue:'',
    //开始时间
    startTime: '开始日期',
    //开始时间选择框
    showStartTime:false,
    //结束时间
    endTime: '结束日期',
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),   
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } 
      return value
    },
    //项目选择框
    showProject:false,
    //项目选择数据
    projectList:[],
    //项目id
    projectId:null,
    //项目名称
    projectName:'请选择项目',
    //生成图片
    showImg: false,
    src: '',
    //当前登录用户
    user: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {    
    let user=app.globalData.userInfo;
    this.setData({
      user: user
    }) 

    //获取列表数据
    this.getList();
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj = {
      selectFields: ['id','orderNo','project','requisitionStaff','requisitionTime','goodsList','state','depart'],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    }

    //查询单号
    if(this.data.searchValue){
      dataObj.orderNo='%' +this.data.searchValue+ '%';
    }

    //查询项目
    if(this.data.projectId){
      dataObj['project.id']=this.data.projectId;
    }

    //申购日期  
    if(this.data.startTime!='开始日期' && this.data.endTime!='结束日期'){
      dataObj.complex=[{
        and: {
          requisitionTime: {
            ">=": this.data.startTime + " 00:00:00",
            "<=": this.data.endTime + " 23:59:59"
          }
        }
      }]  
    }

    let param = {
      isAuth: true,
      className: 'clientPurchaseRequisition',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('申购列表');
        console.log(result);

        //计算价格
        const regexp=/(?:\.0*|(\.\d+?)0+)$/;
        result.forEach(item => {
          let goods=item.goodsList;
          let total=0;
          for(let i=0;i<goods.length;i++){
            total += goods[i].goods.price * goods[i].num;
          }
          //保留两位小数并去掉末尾的0
          item.self_total=total.toFixed(2).replace(regexp,'$1');
        });

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转添加/编辑
  goToAdd({currentTarget}){
    let obj={}

    if(currentTarget.dataset.detail){
      let detail=currentTarget.dataset.detail;
      obj.id=detail.id;
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsApplyAdd/goodsApplyAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '单据删除后，将无法恢复, 是否继续？',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"clientPurchaseRequisition",
        data:{
          id:detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          setTimeout(() => {
            //刷新列表和页码
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //显示开始时间
  onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    if(this.data.endTime!='结束日期'){
      if(e.detail<=this.data.currentEnd){
        this.setData({
          startTime: util.timeFormatDay(e.detail),
          currentStart: e.detail
        })
        this.refreshListAndPage();
      }else{
        Toast.fail('结束日期不能早于开始日期');
      }
    }else{
      this.setData({
        startTime: util.timeFormatDay(e.detail),
        currentStart: e.detail
      })
    } 
    this.onCloseStartTime(); 
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    if(this.data.startTime!='开始日期'){
      if(this.data.currentStart<=e.detail){
        this.setData({
          endTime: util.timeFormatDay(e.detail),
          currentEnd: e.detail
        })
        this.refreshListAndPage();
      }else{
        Toast.fail('结束日期不能早于开始日期');
      }
    }else{
      this.setData({
        endTime: util.timeFormatDay(e.detail),
        currentEnd: e.detail
      })
    }
    this.onCloseEndTime();
  },

  //清除时间
  onCancelTime(){
    this.setData({
      startTime: '开始日期',
      endTime: '结束日期'
    })
    
    this.onCloseStartTime();
    this.onCloseEndTime();
    this.refreshListAndPage();
  },

  //显示项目
  onShowProject(){
    this.setData({
			showProject: true
    })
    this.getProjectList();
  },

  //查询项目
  getProjectList(){
    this.setData({
      projectList: []
    })

    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearchProject){
      param.data.name='%' + this.data.valueSearchProject + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];

        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });

        this.setData({
          projectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏项目
  onCloseProject(){
    this.setData({
      showProject: false,
      valueSearchProject:''
    })
  },

  //确认项目
  onConfirmProject(e){
    this.setData({
      projectId: e.detail.value.id,
      projectName: e.detail.value.text
    })
    this.onCloseProject();
    this.refreshListAndPage();
  },

  //搜索项目
  onChangeProjectVal(e){
    this.setData({
      valueSearchProject: e.detail
    })
    this.getProjectList();
  },

  //清除项目
  onCancelProject(){
    this.setData({
      projectId: null,
      projectName: '请选择项目'
    })
    this.onCloseProject();
    this.refreshListAndPage();
  },

  //跳转详情
  goToDetail({currentTarget}){
    let detail=currentTarget.dataset.detail;

    let obj={
      id: detail.id
    }

    wx.navigateTo({
      url: "/packageA/pages/goodsApplyDetail/goodsApplyDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //生成表格
  onExport({currentTarget}){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '表格生成中...'
    });

    let detail=currentTarget.dataset.detail;
    let goUrl=app.globalData.goUrl;

    wx.downloadFile({
      header: {
        'Content-Type': "application/json;charset=UTF-8",
        'Authorization': 'Bearer ' + app.globalData.loginToken,
      },
      url: goUrl+'material/export/wechatPurchaseOrder?id='+detail.id,
      success: function (res) {
        if(res.statusCode==200){
          Toast.clear();
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            showMenu:true,
            success: function (res) {
            },
            fail:function(){
              Toast.fail('操作失败');
            }
          })
        }
      },
      fail:function(){
        Toast.fail('操作失败');
      }
    })
  },

  //生成图片
  onImg({currentTarget}){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '图片生成中...'
    });

    //显示图片组件
    this.setData({
      showImg: true
    })

    setTimeout(() => {
      let detail=currentTarget.dataset.detail;
      console.log(detail);

      //图片内容
      const wxml = `
      <view class="container">
        <line>111111111111111</text>
      </view>
      `
      const style = {
        container: {
          width: 700,
          heigth: 600,
          backgroundColor: '#ccc'        
        },       
        line:{
          width: 600,
          heigth: 50
        },
        name:{
            width: 200,
            heigth: 40,
            textAlign: 'right'
        },
        word:{
            width: 200,
            heigth: 40
        }
      }
    
      //生成canvas
      this.widget = this.selectComponent('.widget');
      const p1 = this.widget.renderToCanvas({wxml,style});
      p1.then((res) => {			
        this.container = res
      })

      //生成图片
      const p2 = this.widget.canvasToTempFilePath();
      p2.then(res => {
        this.setData({
          src: res.tempFilePath,
          width: this.container.layoutBox.width,
          height: this.container.layoutBox.height
        })  

        //图片保存和分享
        wx.showShareImageMenu({
          path: res.tempFilePath
        })

        //隐藏图片组件
        this.setData({
          showImg: false
        })
      })

      Toast.clear();
    }, 1000);    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})